"use client"

import {Button} from "@/components/ui/button"
import {Card, CardContent, CardDescription, CardHeader, CardTitle} from "@/components/ui/card"
import {Input} from "@/components/ui/input"
import {Label} from "@/components/ui/label"
import {Select, SelectContent, SelectItem, SelectTrigger, SelectValue} from "@/components/ui/select"
import {Switch} from "@/components/ui/switch"
import {Tabs, TabsContent, TabsList, TabsTrigger} from "@/components/ui/tabs"
import {Textarea} from "@/components/ui/textarea"
import {useToast} from "@/hooks/use-toast"
import {AiService} from "@/lib/ai-service"
import {useAppStore, useOpenaiConfig} from "@/lib/store"
import type {ComponentConfig, ComponentFeature, ComponentProp} from "@/lib/types"
import {PlusCircle, Trash2, Wand2} from "lucide-react"
import {useState} from "react"

interface GeneratorPanelProps {
    onGenerate: (code: string) => void
}

export function GeneratorPanel({onGenerate}: GeneratorPanelProps) {
    const { toast } = useToast()
    const openaiConfig = useOpenaiConfig()
    const {selectedModel, isLoading, setIsLoading} = useAppStore()
    const [activeTab, setActiveTab] = useState("basic")
    const [componentName, setComponentName] = useState("MyComponent")
    const [componentType, setComponentType] = useState("basic")
    const [componentDescription, setComponentDescription] = useState("")
    const [prompt, setPrompt] = useState("")
    const [props, setProps] = useState<ComponentProp[]>([])
    const [features, setFeatures] = useState<ComponentFeature[]>([
        {id: "events", name: "事件处理", enabled: false},
        {id: "state", name: "状态管理", enabled: false},
        {id: "lifecycle", name: "生命周期钩子", enabled: false},
        {id: "validation", name: "表单验证", enabled: false},
        {id: "responsive", name: "响应式设计", enabled: false},
        {id: "darkMode", name: "暗色模式", enabled: false},
        {id: "pagination", name: "分页功能", enabled: false},
        {id: "search", name: "搜索功能", enabled: false},
    ])

    const [generating, setGenerating] = useState(false)

    const handleAddProp = () => {
        setProps([
            ...props,
            {
                name: `prop${props.length + 1}`,
                type: "string",
                required: false,
                defaultValue: "",
                description: "",
            },
        ])
    }

    const handleRemoveProp = (index: number) => {
        setProps(props.filter((_, i) => i !== index))
    }

    const handlePropChange = (index: number, field: keyof ComponentProp, value: string | boolean) => {
        const newProps = [...props]
        newProps[index] = {...newProps[index], [field]: value}
        setProps(newProps)
    }

    const handleFeatureToggle = (id: string, enabled: boolean) => {
        setFeatures(features.map((feature) => (feature.id === id ? {...feature, enabled} : feature)))
    }


    const handleGenerate = async () => {
        if (generating) return

        const config: ComponentConfig = {
            name: componentName,
            type: componentType,
            description: componentDescription,
            props,
            features,
        }

        try {
            setGenerating(true)
            setIsLoading(true)

            // 如果有提示词，使用AI生成
            if (prompt.trim()) {
                // 构建提示词
                const featuresList = features
                    .filter((f) => f.enabled)
                    .map((f) => f.name)
                    .join("、")

                const propsList = props
                    .map(
                        (p) =>
                            `${p.name}${p.required ? "(必填)" : ""}: ${p.type}${p.defaultValue ? `, 默认值: ${p.defaultValue}` : ""
                            }${p.description ? ` - ${p.description}` : ""}`,
                    )
                    .join("\n")

                const fullPrompt = `请生成一个名为 ${componentName} 的Vue3组件，类型为${getComponentTypeText(componentType)}。
${componentDescription ? `组件描述: ${componentDescription}` : ""}
${featuresList ? `需要包含的功能: ${featuresList}` : ""}
${propsList ? `组件属性:\n${propsList}` : ""}

用户的额外要求: ${prompt}

请生成完整的Vue3组件代码，使用<script setup lang="ts">语法，并使用TailwindCSS进行样式设计。`

                const code = await AiService.generateComponent(fullPrompt, selectedModel, openaiConfig)
                onGenerate(code)
            } else {
                // 使用模板生成
                import("@/lib/code-generator").then(({CodeGenerator}) => {
                    const code = CodeGenerator.generate(config)
                    onGenerate(code)
                })
            }

            toast({
                title: "组件生成成功",
                description: `已生成 ${config.name} 组件代码`,
            })
        } catch (error) {
            console.error("Error generating component:", error)
            toast({
                title: "生成失败",
                description: error instanceof Error ? error.message : "组件生成失败，请重试",
                variant: "destructive",
            })
        } finally {
            setGenerating(false)
            setIsLoading(false)
        }
    }

    const getComponentTypeText = (type: string): string => {
        switch (type) {
            case "basic":
                return "基础组件"
            case "form":
                return "表单组件"
            case "layout":
                return "布局组件"
            case "data":
                return "数据展示组件"
            case "navigation":
                return "导航组件"
            default:
                return type
        }
    }

    // 示例提示词
    const examplePrompts = [
        "创建一个带有表单验证的用户注册表单",
        "设计一个响应式的产品卡片组件，支持图片、标题、价格和购买按钮",
        "制作一个支持暗色模式的导航栏，包含下拉菜单和移动端适配",
        "生成一个数据表格组件，支持分页、排序和搜索功能",
    ]

    const useExamplePrompt = (example: string) => {
        setPrompt(example)
        setActiveTab("ai")
    }

    return (
        <div className="space-y-6">
            <Card>
                <CardHeader>
                    <CardTitle>组件信息</CardTitle>
                    <CardDescription>定义您想要生成的组件的基本信息</CardDescription>
                </CardHeader>
                <CardContent className="space-y-4">
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div className="space-y-2">
                            <Label htmlFor="component-name">组件名称</Label>
                            <Input
                                id="component-name"
                                value={componentName}
                                onChange={(e) => setComponentName(e.target.value)}
                                placeholder="MyComponent"
                            />
                        </div>
                        <div className="space-y-2">
                            <Label htmlFor="component-type">组件类型</Label>
                            <Select value={componentType} onValueChange={setComponentType}>
                                <SelectTrigger id="component-type">
                                    <SelectValue placeholder="选择组件类型"/>
                                </SelectTrigger>
                                <SelectContent>
                                    <SelectItem value="basic">基础组件</SelectItem>
                                    <SelectItem value="form">表单组件</SelectItem>
                                    <SelectItem value="layout">布局组件</SelectItem>
                                    <SelectItem value="data">数据展示</SelectItem>
                                    <SelectItem value="navigation">导航组件</SelectItem>
                                </SelectContent>
                            </Select>
                        </div>
                    </div>
                    <div className="space-y-2">
                        <Label htmlFor="component-description">组件描述</Label>
                        <Textarea
                            id="component-description"
                            value={componentDescription}
                            onChange={(e) => setComponentDescription(e.target.value)}
                            placeholder="描述组件的功能和用途..."
                            rows={3}
                        />
                    </div>
                </CardContent>
            </Card>

            <Tabs value={activeTab} onValueChange={setActiveTab} className="w-full">
                <TabsList className="grid w-full grid-cols-3">
                    <TabsTrigger value="basic">基本配置</TabsTrigger>
                    <TabsTrigger value="advanced">高级配置</TabsTrigger>
                    <TabsTrigger value="ai">AI 辅助</TabsTrigger>
                </TabsList>

                <TabsContent value="basic" className="space-y-4 mt-4">
                    <Card>
                        <CardHeader>
                            <CardTitle>组件功能</CardTitle>
                            <CardDescription>选择组件需要包含的功能</CardDescription>
                        </CardHeader>
                        <CardContent>
                            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                {features.map((feature) => (
                                    <div key={feature.id} className="flex items-center space-x-2">
                                        <Switch
                                            id={`feature-${feature.id}`}
                                            checked={feature.enabled}
                                            onCheckedChange={(checked) => handleFeatureToggle(feature.id, checked)}
                                        />
                                        <Label htmlFor={`feature-${feature.id}`}>{feature.name}</Label>
                                    </div>
                                ))}
                            </div>
                        </CardContent>
                    </Card>
                </TabsContent>

                <TabsContent value="advanced" className="space-y-4 mt-4">
                    <Card>
                        <CardHeader className="flex flex-row items-center justify-between">
                            <div>
                                <CardTitle>组件属性</CardTitle>
                                <CardDescription>定义组件的属性（Props）</CardDescription>
                            </div>
                            <Button variant="outline" size="sm" onClick={handleAddProp}>
                                <PlusCircle className="h-4 w-4 mr-2"/>
                                添加属性
                            </Button>
                        </CardHeader>
                        <CardContent>
                            {props.length === 0 ? (
                                <div
                                    className="text-center py-4 text-muted-foreground">点击"添加属性"按钮来定义组件属性</div>
                            ) : (
                                <div className="space-y-4">
                                    {props.map((prop, index) => (
                                        <div key={index}
                                             className="grid grid-cols-12 gap-2 items-start border p-3 rounded-md">
                                            <div className="col-span-3">
                                                <Label htmlFor={`prop-name-${index}`} className="text-xs">
                                                    属性名
                                                </Label>
                                                <Input
                                                    id={`prop-name-${index}`}
                                                    value={prop.name}
                                                    onChange={(e) => handlePropChange(index, "name", e.target.value)}
                                                    placeholder="propName"
                                                    className="mt-1"
                                                />
                                            </div>
                                            <div className="col-span-2">
                                                <Label htmlFor={`prop-type-${index}`} className="text-xs">
                                                    类型
                                                </Label>
                                                <Select value={prop.type}
                                                        onValueChange={(value) => handlePropChange(index, "type", value)}>
                                                    <SelectTrigger id={`prop-type-${index}`} className="mt-1">
                                                        <SelectValue placeholder="类型"/>
                                                    </SelectTrigger>
                                                    <SelectContent>
                                                        <SelectItem value="string">string</SelectItem>
                                                        <SelectItem value="number">number</SelectItem>
                                                        <SelectItem value="boolean">boolean</SelectItem>
                                                        <SelectItem value="object">object</SelectItem>
                                                        <SelectItem value="array">array</SelectItem>
                                                        <SelectItem value="function">function</SelectItem>
                                                    </SelectContent>
                                                </Select>
                                            </div>
                                            <div className="col-span-2">
                                                <Label htmlFor={`prop-required-${index}`} className="text-xs">
                                                    是否必需
                                                </Label>
                                                <div className="flex items-center h-10 mt-1">
                                                    <Switch
                                                        id={`prop-required-${index}`}
                                                        checked={prop.required}
                                                        onCheckedChange={(checked) => handlePropChange(index, "required", checked)}
                                                    />
                                                </div>
                                            </div>
                                            <div className="col-span-3">
                                                <Label htmlFor={`prop-default-${index}`} className="text-xs">
                                                    默认值
                                                </Label>
                                                <Input
                                                    id={`prop-default-${index}`}
                                                    value={prop.defaultValue || ""}
                                                    onChange={(e) => handlePropChange(index, "defaultValue", e.target.value)}
                                                    placeholder="默认值"
                                                    className="mt-1"
                                                    disabled={prop.required}
                                                />
                                            </div>
                                            <div className="col-span-1 flex items-end justify-end h-full">
                                                <Button
                                                    variant="ghost"
                                                    size="icon"
                                                    onClick={() => handleRemoveProp(index)}
                                                    className="text-destructive hover:text-destructive/90 hover:bg-destructive/10"
                                                >
                                                    <Trash2 className="h-4 w-4"/>
                                                </Button>
                                            </div>
                                            <div className="col-span-12 mt-2">
                                                <Label htmlFor={`prop-description-${index}`} className="text-xs">
                                                    描述
                                                </Label>
                                                <Input
                                                    id={`prop-description-${index}`}
                                                    value={prop.description || ""}
                                                    onChange={(e) => handlePropChange(index, "description", e.target.value)}
                                                    placeholder="属性描述"
                                                    className="mt-1"
                                                />
                                            </div>
                                        </div>
                                    ))}
                                </div>
                            )}
                        </CardContent>
                    </Card>
                </TabsContent>

                <TabsContent value="ai" className="space-y-4 mt-4">
                    <Card>
                        <CardHeader>
                            <CardTitle>AI 辅助生成</CardTitle>
                            <CardDescription>使用自然语言描述您想要的组件，AI将为您生成代码</CardDescription>
                        </CardHeader>
                        <CardContent className="space-y-4">
                            <div className="space-y-2">
                                <Label htmlFor="ai-prompt">提示词</Label>
                                <Textarea
                                    id="ai-prompt"
                                    value={prompt}
                                    onChange={(e) => setPrompt(e.target.value)}
                                    placeholder="描述您想要的组件功能、样式和行为..."
                                    rows={6}
                                />
                                <p className="text-xs text-muted-foreground">
                                    提示：描述越详细，生成的组件越符合您的需求。AI会结合您在基本信息和配置中的设置。
                                </p>
                            </div>

                            <div className="space-y-2">
                                <Label>示例提示词</Label>
                                <div className="flex flex-wrap gap-2">
                                    {examplePrompts.map((example, index) => (
                                        <Button
                                            key={index}
                                            variant="outline"
                                            size="sm"
                                            onClick={() => useExamplePrompt(example)}
                                            className="text-xs"
                                        >
                                            {example}
                                        </Button>
                                    ))}
                                </div>
                            </div>
                        </CardContent>
                    </Card>
                </TabsContent>
            </Tabs>

            <div className="flex justify-end">
                <Button onClick={handleGenerate} size="lg" disabled={isLoading || generating}>
                    {isLoading || generating ? (
                        <>
                            <svg
                                className="animate-spin -ml-1 mr-3 h-5 w-5 text-white"
                                xmlns="http://www.w3.org/2000/svg"
                                fill="none"
                                viewBox="0 0 24 24"
                            >
                                <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor"
                                        strokeWidth="4"></circle>
                                <path
                                    className="opacity-75"
                                    fill="currentColor"
                                    d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
                                ></path>
                            </svg>
                            生成中...
                        </>
                    ) : (
                        <>
                            <Wand2 className="mr-2 h-5 w-5"/>
                            生成组件
                        </>
                    )}
                </Button>
            </div>
        </div>
    )
}
